pub mod dynamic_task_scheduler;
pub mod task;

use std::time::Duration;
use redis::aio::MultiplexedConnection;
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};
use tokio::time::interval;
use tracing::warn;
use crate::entity::sys_scheduled_task;
use crate::handler::order_handler;
use crate::scheduler::dynamic_task_scheduler::DynamicTaskScheduler;

pub struct TaskScheduler {
    db: DatabaseConnection,
    conn: MultiplexedConnection
}

impl TaskScheduler {
    pub fn new(db: DatabaseConnection, conn: MultiplexedConnection) -> Self {
        Self { db, conn }
    }

    // 轮询并执行到期的任务
    pub async fn poll_and_execute_tasks(&self) -> Result<(), Box<dyn std::error::Error>> {

        // 设置15分钟的间隔时间 (15 * 60 = 900秒)
        let mut interval = interval(Duration::from_secs(900));

        loop {

            // 获取当前时间
            let current_time = chrono::Utc::now().naive_utc();
            // 查找所有需要执行的任务
            let active_tasks = sys_scheduled_task::Entity::find()
                .filter(sys_scheduled_task::Column::Status.eq("active"))
                .filter(sys_scheduled_task::Column::NextRunTime.lte(current_time))
                .all(&self.db)
                .await?;

            // 执行每个到期的任务
            for task in active_tasks {
                match task.task_type.as_str() {

                    "cron" => {

                    }
                    "once" => {

                    }
                    _ => {
                        warn!("未知任务类型: {}", task.task_type);
                    }
                }
            }

            // 等待下一个时间间隔
            interval.tick().await;
        }
    }
}

